package com.mtt.erp.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.mtt.erp.common.domain.MttErpConstant;
import com.mtt.erp.common.domain.QueryRequest;
import com.mtt.erp.common.exception.MttErpException;
import com.mtt.erp.common.utils.IdsPre;
import com.mtt.erp.common.utils.MttErpUtil;
import com.mtt.erp.common.utils.SortUtil;
import com.mtt.erp.file.dto.ImageDto;
import com.mtt.erp.file.service.GoodsFileInfoService;
import com.mtt.erp.goods.dao.MabFileMapper;
import com.mtt.erp.goods.domain.MaaFile;
import com.mtt.erp.goods.dao.MaaFileMapper;
import com.mtt.erp.goods.dto.*;
import com.mtt.erp.goods.service.IMaaFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mtt.erp.goods.service.IMabFileService;
import com.mtt.erp.goods.vo.GoodsVo;
import com.mtt.erp.goods.vo.MaaFileVo;
import com.mtt.erp.goods.vo.MabFileVo;
import com.mtt.erp.system.domain.User;
import com.mtt.erp.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * @author MrBird
 */
@Service
@Slf4j
public class MaaFileServiceImpl extends ServiceImpl<MaaFileMapper, MaaFile> implements IMaaFileService {

    @Value("${erp.max.batch.insert.num}")
    private int batchInsertMaxNum;
    @Value("${goods.image.domainName}")
    private String domainName;

    @Autowired
    GoodsFileInfoService goodsFileInfoService;
    @Autowired
    IMabFileService mabFileService;
    @Resource
    MaaFileMapper maaFileMapper;
    @Resource
    MabFileMapper mabFileMapper;
    @Autowired
    UserService userService;

    @Override
    public IPage<MaaPageDto> findMaa(QueryRequest request, MaaDto maaDto) {
       maaDto.setMaacuser(String.valueOf(MttErpUtil.getCurrentUser().getUserId()));
       Page<MaaPageDto> page = new Page<>(request.getPageNum(), request.getPageSize());
       SortUtil.handlePageSort(request, page, "id",MttErpConstant.ORDER_DESC,true);
       IPage<MaaPageDto> maaPageDtoIPage = maaFileMapper.selectPageVo(page, maaDto);
       List<MaaPageDto> records = maaPageDtoIPage.getRecords();
       for(MaaPageDto dto:records){
           // 主商品图片增加前缀
           if (dto.getImageUrl() != null){
               dto.setImageUrl(this.domainName + dto.getImageUrl());
           }
           dto.setKey(dto.getId());
           List<MaaPageDto> mabPageDtos = mabFileMapper.selectListVo(dto.getSku());
           for (MaaPageDto mabPageDto: mabPageDtos) {
               // 子商品图片增加前缀
               if(mabPageDto.getImageUrl() != null){
                   mabPageDto.setImageUrl(this.domainName + mabPageDto.getImageUrl());
               }
               mabPageDto.setKey(mabPageDto.getId());
           }
           dto.setChildren(mabPageDtos);
       }
       return maaPageDtoIPage;
    }

    @Override
    @Transactional
    public Boolean createMaa(MaaCreateDto dto) throws MttErpException {
        // 添加商品
        MaaFile maaFile= MaaFile.builder().build();
        BeanUtils.copyProperties(dto,maaFile);
        // 生成19位流水
        maaFile.setMaa00(generateId());
        maaFile.setMaacdate(LocalDateTime.now());
        //商品是属于哪一个用户的
        Long currentUserId = MttErpUtil.getCurrentUser().getUserId();
        maaFile.setMaacuser(currentUserId.toString());
        try {
            return this.save(maaFile);
        }catch (Exception e){
            log.error("新增商品失败");
            throw new MttErpException("新增商品失败");
        }
    }

    @Override
    @Transactional
    public Boolean updateMaa(MaaUpdateDto dto) throws MttErpException {
        // 判断主图是否时文件名
        if(dto.getMaa17()!= null && dto.getMaa17().contains(this.domainName)){
            dto.setMaa17(null);
        }
        MaaFile maaFile= MaaFile.builder().build();
        BeanUtils.copyProperties(dto,maaFile);
        Long currentUserId = MttErpUtil.getCurrentUser().getUserId();
        maaFile.setMaamdate(LocalDateTime.now());
        maaFile.setMaamuser(currentUserId.toString());
        try {
            return this.updateById(maaFile);
        }catch (Exception e){
            log.error("修改商品失败");
            throw new MttErpException("修改商品失败");
        }
    }

    @Override
    public GoodsVo findFiles(MaaFile maaFile) {
        GoodsVo goodsVo = GoodsVo.builder().build();
        // 主图
        if (StringUtils.isNotBlank(maaFile.getMaa17())) {
            List<String> keys = Lists.newArrayList();
            keys.add(maaFile.getMaa17());
            List<ImageDto> fileListM = goodsFileInfoService.findImageListByIkeyS(keys);
            goodsVo.setFileListM(fileListM);
        } else {
            goodsVo.setFileListM(Lists.newArrayList());
        }
        // 附图
        if (StringUtils.isNotBlank(maaFile.getMaa20())) {
            String maa20Str = maaFile.getMaa20();
            String[] maa20s = maa20Str.split(",");
            List<String> imageKes = Arrays.asList(maa20s);
            List<ImageDto> fileListF = goodsFileInfoService.findImageListByIkeyS(imageKes);
            goodsVo.setFileListF(fileListF);
        } else {
            goodsVo.setFileListF(Lists.newArrayList());
        }
        // 视频
        if (StringUtils.isNotBlank(maaFile.getMaa18())) {
            List<String> keys = Lists.newArrayList();
            keys.add(maaFile.getMaa18());
            List<ImageDto> fileListVideo = goodsFileInfoService.findImageListByIkeyS(keys);
            goodsVo.setFileListVideo(fileListVideo);
        } else {
            goodsVo.setFileListVideo(Lists.newArrayList());
        }
        return goodsVo;
    }

    @Override
    public GoodsVo beforeEditInit(String id){
        // 主商品信息
        MaaFile maaFile = this.getById(id);
        if(maaFile!=null){
            // 查询主商品file
            GoodsVo goodsVo = findFiles(maaFile);
            // 主商品
            MaaFileVo maaFileVo = MaaFileVo.builder().build();
            BeanUtils.copyProperties(maaFile,maaFileVo);
            goodsVo.setMaaFile(maaFileVo);
            //子商品集合
            List<MabFileVo> mabList =this.mabFileService.findMabFileListByMab01(maaFile.getMaa01());
            goodsVo.setDataSourceMabChild(mabList);
            return goodsVo;
        }else{
            return null;
        }
    }
    
    @Override
    @Transactional
    public Boolean putAway(String[] maaIds) throws MttErpException {
        List<MaaFile> maaFileList = Lists.newLinkedList();
        for (String maaId : maaIds) {
            //批量构造上架的商品对象
            MaaFile maaFile = MaaFile.builder().maa00(maaId).maaacti("Y").build();
            maaFileList.add(maaFile);
        }
        try {
            return this.updateBatchById(maaFileList);
        } catch (Exception e){
            log.error("上架商品失败");
            throw new MttErpException("上架商品失败");
        }
    }

    @Override
    @Transactional
    public Boolean soldOut(String[] maaIds) throws MttErpException {
        List<MaaFile> maaFileList = Lists.newLinkedList();
        for (String maaId : maaIds) {
            //批量构造上架的商品对象
            MaaFile maaFile = MaaFile.builder().maa00(maaId).maaacti("N").build();
            maaFileList.add(maaFile);
        }
        try {
            return this.updateBatchById(maaFileList);
        }catch (Exception e){
            log.error("下架商品失败");
            throw new MttErpException("下架商品失败");
        }
    }

    @Override
    public MaaFile getBymaa01(String maa01) {
        return baseMapper.selectOne(new LambdaQueryWrapper<MaaFile>().eq(MaaFile::getMaa01, maa01));
    }

    /**
     * 定时任务使用
     * 查询所有主商品中sku列表
     * @return
     */
    public List<MaaFileTaskDto> getMaaList(){
        List<MaaFileTaskDto> maaFileTaskDtos = Lists.newArrayList();
        List<MaaFile> list = this.list();
        for (MaaFile maaFile : list) {
            MaaFileTaskDto maaFileTaskDto = MaaFileTaskDto.builder().build();
            BeanUtils.copyProperties(maaFile,maaFileTaskDto);
            maaFileTaskDtos.add(maaFileTaskDto);
        }
        return maaFileTaskDtos;
    }


    /**
     * 获取SKU
     *
     * @return
     */
    @Override
    public String getSKU() {
        Long currentUserId = MttErpUtil.getCurrentUser().getUserId();
        User user = userService.findById(currentUserId.toString());
        String code = user.getCode();
        String returnNum = "";
        LambdaQueryWrapper<MaaFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MaaFile::getMaacuser, currentUserId);
        int count = this.count(queryWrapper);
        count++;
        String countStr = count + "";
        int length = countStr.length();
        int lengthLeft = 4 - length;
        if (lengthLeft == 0) {
            returnNum = countStr;
        } else if (lengthLeft == 1) {
            returnNum = "0" + countStr;
        } else if (lengthLeft == 2) {
            returnNum = "00" + countStr;
        } else if (lengthLeft == 3) {
            returnNum = "000" + countStr;
        }
        return code + returnNum;
    }

    /**
     * 生成商品流水号
     * @return
     */
    public String generateId() {
        String sku=getSKU();
        String maaIdPre = IdsPre.getMaaId();
        return sku.substring(0,4)+maaIdPre+sku.substring(4,sku.length());
    }
}

